﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>用户信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_UserId_FormItem" prop="Entity.UserId">
								<template #label>
									<WtmLabelTooltip label="绑定用户" tooltip="关联的系统用户对象" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.UserId" clearable class="width100">
									<el-option v-for="item in stateData.AllFrameworkUsers" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>菜单信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_MenuId_FormItem"
								prop="Entity.MenuId"
								:rules="[{ required: true, message: '菜单ID为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="菜单ID" tooltip="收藏菜单的唯一标识符" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.MenuId" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_MenuName_FormItem"
								prop="Entity.MenuName"
								:rules="[{ required: true, message: '菜单名称为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="菜单名称" tooltip="收藏菜单的显示名称" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.MenuName" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_MenuIcon_FormItem" prop="Entity.MenuIcon">
								<template #label>
									<WtmLabelTooltip label="菜单图标" tooltip="收藏菜单显示的图标样式" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.MenuIcon" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_MenuUrl_FormItem" prop="Entity.MenuUrl">
								<template #label>
									<WtmLabelTooltip label="菜单URL" tooltip="收藏菜单的访问地址路径" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.MenuUrl" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_SortOrder_FormItem" prop="Entity.SortOrder">
								<template #label>
									<WtmLabelTooltip label="排序" tooltip="收藏菜单的显示排序序号，数值越小越靠前" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.SortOrder" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, nextTick, type ComponentInternalInstance } from 'vue';
import { SysUserFavoriteApi as api } from '/@/views/_admin/sysuserfavorite/api';
import other from '/@/utils/other';
import { ISysUserFavoriteVm } from '/@/views/_admin/sysuserfavorite/api/interface';
import { IViewModel } from '/@/types/common';

// 常量定义

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);

const stateData = reactive<IViewModel<ISysUserFavoriteVm>>({
	vmModel: {
		Entity: {
			UserId: null,
			MenuId: null,
			MenuName: null,
			MenuIcon: null,
			MenuUrl: null,
			SortOrder: null,
		},
	},

	AllFrameworkUsers: [] as any[],
});

// 计算属性

// 公共的响应处理函数
const handleApiResponse = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
	}

	emit('refresh');

	// 统一处理ID设置
	if (response?.Entity?.ID) {
		stateData.vmModel.Entity = response.Entity;
	} else if (response?.ID) {
		stateData.vmModel.Entity.ID = response.ID;
	}

	// 根据操作类型处理不同逻辑
	if (isSubmit) {
		closeDialog();
	} else {
		hasSavedOnce.value = true;
	}

	loading.value = false; // 重置loading状态

	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的表单提交函数
const submitForm = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response, isSubmit))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	submitForm(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {
			emit('refresh');
			closeDialog();
		},
		false
	);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 加载选择列表数据
const loadSelectListData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysUserFavorite/GetFrameworkUsers', [], false).then((x) => {
			stateData.AllFrameworkUsers = x;
		}),
	]);
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadSelectListData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: !hasSavedOnce.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
